<template>
    <div id="mars3dContainer" class="mars3d-container"></div>
</template>

<script>
import {GetStationByBasinID } from '../../api/https'
import "mars3d-cesium/Build/Cesium/Widgets/widgets.css"
import "mars3d/mars3d.css"
import * as mars3d from 'mars3d'
import * as Cesium from "mars3d-cesium"

export default {
    name: "MarsMap",
    props: {
        basinId: {
            type: [String, Number],
            default: ''
        },
        isHome: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            map: null,
            graphicLayer: null, 
            imageLayer: null,
            terrainTimeout:null
        }
    },
    mounted() {
        
       
    },
    activated(){
        window.CESIUM_BASE_URL = '/mars3d-cesium/';
        this.initMap()
    },
    beforeDestroy() {
        delete window.CESIUM_BASE_URL;
        this.destroyMap()
    },
    deactivated() {
        delete window.CESIUM_BASE_URL;
        this.destroyMap()
    },

    methods: {
        initMap() {
            if (this.map) return
            const mapOptions = {
                scene: {
                    center: {
                        lat: 34.900,
                        lng: 93.175,
                        alt: 6134195,
                        heading: 0,
                        pitch: -90
                    },
                    shadows: false,
                    removeDblClick: true,
                    sceneMode: 3,
                    globe: {
                        baseColor: '#fff',
                        showGroundAtmosphere: false,
                        enableLighting: false
                    },
                    cameraController: {
                        zoomFactor: 3.0,
                        minimumZoomDistance: 5,
                        maximumZoomDistance: 50000000,
                        enableRotate: true,
                        enableTranslate: true,
                        enableTilt: true,
                        enableZoom: true
                    }
                },
                control: {
                    homeButton: true,
                    infoBox: true,
                    selectionIndicator: true,
                    contextmenu: { hasDefault: true },
                    compass: { top: '50px', right: '5px' }
                },
                terrain: {
                    url: 'http://data.mars3d.cn/terrain',
                    show: true
                },
                basemaps: [
                    {
                        name: "天地图影像",
                        type: "tdt",
                        layer: "img_d",
                        show: true
                    }
                ],
                layers: [
                    {
                        name: "天地图注记",
                        type: "tdt",
                        layer: "img_z",
                        show: true
                    }
                ]
            }
            this.map = new mars3d.Map("mars3dContainer", mapOptions)
            this.graphicLayer = new mars3d.layer.GraphicLayer({ id: 'dynamicDataLayer' })
            this.map.addLayer(this.graphicLayer)
            this.graphicLayer.bindPopup(function (event) {
                const attr = event.graphic.attr || {}
                return mars3d.Util.getTemplateHtml({ title: "电站信息", template: "all", attr: attr })
            })
            this.map.addControl(
                new mars3d.control.LocationBar({
                     template: "<div>经度:{lng}</div><div>纬度:{lat}</div> <div>海拔：{alt}米</div> <div>层级：{level}</div><div>方向：{heading}度</div> <div>俯仰角：{pitch}度</div><div>视高：{cameraHeight}米</div>"
                })
            )
            this.setupLayerEvents()

            this.map.on(mars3d.EventType.terrainLoaded, () => {
              this.loadBasinStations();
            });

            this.terrainTimeout = setTimeout(() => {
              if (!this.map.scene.terrainProvider.ready) {
                  this.loadBasinStations();
              }
          }, 2000);
        },

        setupLayerEvents() {
            this.graphicLayer.on(mars3d.EventType.mouseOver, (event) => { 
                const graphic = event.graphic
                if (graphic) {
                    graphic.openPopup() 
                }
            })

            this.graphicLayer.on(mars3d.EventType.mouseOut, (event) => { 
                const graphic = event.graphic
                if (graphic) {
                    graphic.closePopup()
                }
            })

            this.graphicLayer.on(mars3d.EventType.click, (event) => {
                if (this.map.camera.positionCartographic.height > 90000) {
                    const graphic = event.graphic
                    graphic.closePopup()
                    if (graphic) {
                        const position = graphic.positionShow
                        this.map.flyToPoint(position, {
                            radius: 4000,
                            duration: 4,
                        })
                    } else {
                        // 单击了聚合的点
                        const arrEntity = event.pickedObject.id
                        this.map.flyToPoint(arrEntity)
                    }
                }
            })
        },

       async loadBasinStations() {
        try {
            const res = await GetStationByBasinID(this.basinId);
            if (!res?.data?.length) {
                console.warn("无站点数据");
                return;
            }

            const firstStation = res.data[0];
            if (!firstStation.location) {
                console.error("站点无坐标信息");
                return;
            }

            const coords = firstStation.location.split(",");
            const lng = parseFloat(coords[0].trim());
            const lat = parseFloat(coords[1].trim()); 
            const targetPoint = new mars3d.LngLatPoint(lng, lat, 200000);
            this.renderStationData(res.data, lat, lng, 200000);
            await new Promise(resolve => {
                this.map.flyToPoint(targetPoint, {
                    radius: 200000,  // 200公里高度
                    duration: 1,
                    pitch: -90,
                    heading: 0,
                    complete: resolve
                });
            });
        } catch (err) {
            console.error("定位流程错误:", err);
        } finally {
            clearTimeout(this.terrainTimeout);
            this.terrainTimeout = null
        }
    },

    renderStationData(stationData, lat, lng, alt) {
        if (!this.graphicLayer) return;
        this.graphicLayer.clear();
        stationData.forEach(station => {
            station.statusName = station.status == 0 ? '未接入' : '已接入';
        });
        stationData.forEach(station => {
            if (!station.location) return;

            const [jd, wd] = station.location.split(',').map(Number);
            this.addStationMarker(station, jd, wd);
        });
        if (lat && lng) {
            this.map.flyToPoint({
                lat: lat,
                lng: lng,
                alt: alt,
                heading: 0,
                pitch: -90
            }, {
                duration: 2,
            });
        }
    },
    addStationMarker(station, lng, lat) {
        const marker = new mars3d.graphic.BillboardPrimitive({
            name: station.stationName,
            id: station.id,
            status: station.status,
            position: [lng, lat],
            style: {
                image: require("@/assets/image/mark5.png"),
                scale: 1,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                clampToGround: true,
                label: {
                    text: station.stationName,
                    font_size: 14,
                    color: Cesium.Color.AZURE,
                    outline: true,
                    outlineColor: Cesium.Color.BLACK,
                    outlineWidth: 4,
                    horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    pixelOffset: new Cesium.Cartesian2(15, 0),
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 4500000)
                }
            },
            attr: {
                "电站名称": station.stationName,
                "电站图片": `<img style="max-width:200px" src="${station.address}">`,
                "电站详情": this.formatStationDetails(station)
            }
        })
        this.graphicLayer.addGraphic(marker)
    },
    formatStationDetails(data) {
        return `
            <div class="station-info">
                <div>库容：${data.reservoirCapacity || '无'}</div>
                <div>坝型：${data.damCategory || '无'}</div>
                <div>坝高：${data.damHeight || '无'}</div>
                <div>装机容量：${data.installation || '无'}</div>
                <div>投产时间：${data.productionTime || '无'}</div>
                <div>状态：${data.statusName || '无'}</div>
            </div>
        `
    },
    destroyMap() {
        if (this.map) {
            this.map.off()
            this.map.destroy()
            console.log('执行了')
            this.map = null
            this.graphicLayer = null

            const container = document.getElementById('mars3dContainer')
            if (container) {
                container.innerHTML = ''
            }

            clearTimeout(this.terrainTimeout);
            this.terrainTimeout = null

            if (window.Cesium) {
                window.Cesium = undefined;
            }
        }
    },
   
    async updateMapData() {
        try {
            const res = await GetStationByBasinID(this.basinId);
            const firstStation = res.data[0];
            const [lng, lat] = firstStation.location.split(",").map(coord => {
                const num = parseFloat(coord.trim());
                if (isNaN(num)) throw new Error(`坐标解析失败: ${coord}`);
                return num;
            });

            const targetPoint = new mars3d.LngLatPoint(lng, lat, 200000);
            this.graphicLayer.clear();
            this.renderStationData(res.data, lat, lng, 200000);

            this.map.flyToPoint(targetPoint, {
                radius: 5000,          
                duration: 1,          
                pitch: -90,          
                heading: 0,    
            });

        } catch (err) {
            console.error("定位失败:", err);
        }
    }
    }
}
</script>

<style scoped>
.mars3d-container {
    position: relative;
    width: 100%;
    height: 460px;
    border-radius: 8px;
}
</style>

<style lang="scss">
.mars3d-popup {
    z-index: 99999999 !important; 
    max-width: none !important; 
    
    .mars3d-popup-content {
        overflow: visible !important;
    }
}

.station-info {
    width: 100%;
    div {
        padding-left: 80px;
    }
}

.mars3d-divGraphic {
    top: -30px !important;
}
.custom-popup {
    position: fixed;
    z-index: 99999;
    background: white;
    border: 1px solid #ccc;
    padding: 10px;
    max-width: 300px;
}
</style>